const app = getApp();
import LoginStore from '../../pages/login/store.js';
import Swiper from '../../pages/detail/swiperInfo.js';
import {reqHeader } from '../../utils/util.js';
let getDefaultData = function() {
  return {
    listData: [],
    hasNext: true
  }
}
Component({
  properties: {
    data: {
      type: Object,
      value: '',
      observer: function(newVal, oldVal, changedPath) {
        
      }
    },
    urlStr: {
      type: String,
      value: '',
      observer: function(newVal, oldVal, changedPath) {
        
      }
    },
    params: {
      type: Object,
      value: {},
      observer: function(newVal, oldVal, changedPath) {
        if (newVal.page == 1) {
          this.setData(getDefaultData())
        }
        if (newVal.page && this.data.hasNext) {
          this._loadData(newVal);
        }
      }
    },
    fromType: {
      type: String,
      value: '',
      observer: function (newVal, oldVal, changedPath) {

      }
    },
    fromResourceId: {
      type: String,
      value: '',
      observer: function (newVal, oldVal, changedPath) {

      }
    },
    maxlen: {
      type: Number,
      value: null,
      observer: function (newVal, oldVal, changedPath) {

      }
    },
    totalPageUrl: {
      type: String,
      value: null
    }
  },

  /**
   * 组件的初始数据
   */
  data: getDefaultData(),

  /**
   * 组件的方法列表
   */
  methods: {
    toPhotoDetail: function(e) {
      let item = e.currentTarget.dataset.item;
      if (item.resourceType == 4 ? item.videoInfo.auditState == 0 : item.state == 1){
        return;
      }
      
      Swiper.setData({
        imgUrls: this.data.listData,
        urlStr: this.properties.urlStr,
        params: this.properties.params,
        hasNext: this.data.hasNext,
        selectedID: item.id
      });

      let urlStr = `/pages/detail/detail?id=${item.id}&resourceType=${item.resourceType}&fromType=${this.properties.fromType}&fromResourceId=${this.properties.fromResourceId}`;
      if (item.resourceType == 4){
        urlStr+= '&type=share'
      }
      if (item.resourceType == 2) {
        urlStr = `/pages/graphicDetail/graphicDetail?id=${item.id}&resourceType=${item.resourceType}`
      }
      let pageList = getCurrentPages();
      if (pageList.length >= 8){
        wx.redirectTo({
          url: urlStr,
        })
      }else{
        wx.navigateTo({
          url: urlStr
        });
      }
    },
    greedoLayout: function(listData) {
      let me = this
      let mContentWidth = app.globalData.screenWidth - 24;
      let mMaxRowHeight = 200

      let currentRowHeight = mMaxRowHeight
      let row = 0
      let pos = 0
      let currentRowAspectRatio = 0.0
      let size = listData.length
      let itemAspectRatios = []
      let itemAspectRatiosIndex = []
      for (let i = 0; i < size; i++) {
        let width = listData[i].width || 355;
        let height = listData[i].height || 200;
        listData[i].aspectRatio = width / height
      }

      while (pos < size) {
        let posAspectRatio = listData[pos].aspectRatio
        currentRowAspectRatio += posAspectRatio
        itemAspectRatios.push(posAspectRatio)
        itemAspectRatiosIndex.push(pos)


        currentRowHeight = me.calculateHeight(mContentWidth, currentRowAspectRatio)

        let isRowFull = currentRowHeight <= mMaxRowHeight

        if (isRowFull) {
          let rowChildCount = itemAspectRatios.length

          let availableSpace = mContentWidth
          for (let i = 0; i < rowChildCount; i++) {
            let itemWidth = me.calculateWidth(currentRowHeight, itemAspectRatios[i])
            if (itemWidth > availableSpace) {
              itemWidth = availableSpace
            }
            listData[itemAspectRatiosIndex[i]].width2 = itemWidth - 8
            listData[itemAspectRatiosIndex[i]].height2 = currentRowHeight - 8
            availableSpace -= itemWidth
          }
          itemAspectRatios = []
          itemAspectRatiosIndex = []
          currentRowAspectRatio = 0.0
        } else {
          if (pos == size - 1) {
            let rowChildCount = itemAspectRatios.length
            if (rowChildCount == 1) {
              let itemWidth = me.calculateWidth(mContentWidth / 3, itemAspectRatios[0])
              listData[itemAspectRatiosIndex[0]].width2 = itemWidth - 8
              listData[itemAspectRatiosIndex[0]].height2 = mContentWidth / 3 - 8
            } else {
              let availableSpace = mContentWidth
              for (let i = 0; i < rowChildCount; i++) {
                let itemWidth = me.calculateWidth(mMaxRowHeight, itemAspectRatios[i])
                if (itemWidth > availableSpace) {
                  itemWidth = availableSpace
                }
                listData[itemAspectRatiosIndex[i]].width2 = itemWidth - 8
                listData[itemAspectRatiosIndex[i]].height2 = mMaxRowHeight - 8
                availableSpace -= itemWidth
              }
            }
          }
        }
        pos++
      }
    },

    calculateWidth: function(itemHeight, aspectRatio) {
      return parseInt(Math.ceil(itemHeight * aspectRatio))
    },

    calculateHeight: function(itemWidth, aspectRatio) {
      return parseInt(Math.ceil(itemWidth / aspectRatio))
    },

    _loadData: function(params) {
      let me = this;
      let userAccountInfo = LoginStore.userInfo || {};
      params['access_token'] = userAccountInfo.access_token;
      wx.request({
        url: this.properties.urlStr,
        data: params,
        header: reqHeader,
        success: function(res) {
          res = res.data;
          if (res.status == 200) {
            let hasNext = true;
            if (!res.data.length || res.data.length < (params.size || 20)) {
              hasNext = false;
            }
            let listData = me.data.listData.concat(res.data);
            me.greedoLayout(listData);
            me.setData({
              listData: listData,
              hasNext: hasNext
            })
          } else {
            console.log(res.message);
          }
        }
      });
    }
  }
})